﻿using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Model;
using Model.eums;
using Model.Model;
using Model.View;

namespace Utils.UserHelper;

public class UserRegister
{
    public static async Task<(bool, string)> Register(RegisterModel user)
    {
        await using var db = new DataDbContent();
        var havingInfo = await db.LoginUser!
            .FirstOrDefaultAsync(e => e.Account == user.Account);
        if (havingInfo is not null)
            return (false, "账户已经存在");
        var (result, message) = RegisterHelper.RuleCheck(user.Account!, user.Password!);
        if (result)
        {
            Task.Factory.StartNew(async () => { await SaveSqlUser(user); });
        }

        return (result, message);
    }

    private static async Task SaveSqlUser(RegisterModel user)
    {
        await using var db = new DataDbContent();
        await db.LoginUser!.AddAsync(new LoginModel
        {
            UserName = user.UserName,
            Account = user.Account,
            Password = user.Password,
            CreateDateTime = DateTime.Now,
            Auth = user.Auth
        });
        await db.SaveChangesAsync();
    }
}